import { useEffect, useState } from "react";
import { EventEmitter } from 'events'

const event = new EventEmitter();


const Cache: Record<string | number | symbol, any> = {}

/**
 * 调整钩子数据，并触发更新
 * @param {String} key 绑定键
 * @param {Function} getFunction 绑定获取函数
 */
export function onGetCache(key: string, getFunction: () => void) {
  Object.defineProperty(Cache, key, { get: getFunction, configurable: true });
  event.emit(key, Cache[key])
}

/**
 * 订阅钩子数据
 * @param {String} key 订阅钩子键
 * @returns 钩子值
 */
export function useCacheState(key: string) {
  const [state, setState] = useState(Cache[key])

  useEffect(() => {
    const callback = () => setState(Cache[key]);
    event.on(key, callback)
    return () => {
      event.off(key, callback)
    }
  }, [key])

  return state
}


